// App.js
import axios from "axios";
import React, { useState, useEffect } from "react";

const flagStyle = {
  width : "180px"
}

const ShowCountry = ({ country }) => {
  const {name,capital,population,flag} = country
  const languages = Object.values(country.languages)

  return (
    <div>
      <h1>{name.common}</h1>
      <p>capital {capital}</p>
      <p>population {population}</p>
      <h2>Spoken Languages</h2>
      <ul>
        {languages.map((item,index) => <li key={index}>{item}</li>)}
      </ul>
      <img src={flag} alt="flag" style={flagStyle}></img>
    </div>
  )
}

const App = () => {
  const [filter, setFilter] = useState('')
  const [countries, setCountries] = useState([])

  useEffect(() => {
    if (filter !== "") {
      axios
        .get(`https://restcountries.com/v3.1/name/${filter}`)
        .then((response) => {
          setCountries(response.data)
        })
    }
  },[filter])
  console.log(countries)

  const handleFilterChange = (event) => {
    event.preventDefault()
    setFilter(event.target.value)
  }

  return (
    <div>
      <div>
        find countries <input value={filter} onChange={handleFilterChange}></input>
      </div>
      <div>
        {countries.length > 10 && <p>too many matches, specify another filter</p>}
        {countries.length < 10 && countries.length !== 1 && countries.map((country) =>
          <div key={country.name.common}>{country.name.common}</div>
        )}
        {countries.length === 1 &&  <ShowCountry country={countries[0]}/>}
      </div>
    </div>
  );
}

export default App;

// index.js
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />,document.getElementById('root'));

